<?php
namespace App\Core\Configure;


use App\Core\ConfigureInterface;
use App\Exception\ConfigureException;

class PhpConfig implements ConfigureInterface
{
    /**
     * @var array 配置文件目录
     */
    private $_configPath = [];

    private $_configures = [];

    private $_extension = '.php';

    /**
     * 设置配置文件扩展名
     *
     * @param string $extension
     * @return void
     */
    public function setFileExtension($extension)
    {
        $this->_extension = $extension;
    }

    /**
     * 注册配置文件目录
     *
     * @param array $paths
     * @return void
     */
    public function registerConfigPath($paths)
    {
        $this->_configPath = $paths;
    }

    public function get($name, $file)
    {
        if (!isset($this->_configures[$file])) {
            $this->_configures[$file] = $this->loadConfig($file);
        }
        $config = $this->_configures[$file];
        return isset($config[$name]) ? $config[$name] : null;
    }

    public function set($name, $value, $file)
    {
        if (!isset($this->_configures[$file])) {
            $this->_configures[$file] = [];
        }
        $this->_configures[$file][$name] = $value;
    }

    public function delete($name, $file)
    {
        if (isset($this->_configures[$file][$name])) {
            unset($this->_configures[$file][$name]);
        }
    }

    /**
     * 加载配置文件
     *
     * @param string $file
     * @return array
     * @throws ConfigureException
     */
    protected function loadConfig($file)
    {
        if (empty($this->_configPath)) {
            throw new ConfigureException('没有设置配置文件目录');
        }
        $fileName = $file . $this->_extension;
        $config = [];
        foreach ($this->_configPath as $path) {
            $configFile = $path . $fileName;
            if (file_exists($configFile)) {
                include $configFile;
            }
        }
        return $config;
    }
}